package memdb

import (
	"time"
)

type MqttDBStr struct {
	Data  string
	Time  int64
	Line  bool
	DevID string
}
type MqttDBMap struct {
	DB map[string]*MqttDBStr
}

//mqttTopic 数据
var MqttDBList MqttDBMap

func (m *MqttDBMap) Add(devId, tn, d string, l bool, t int64) {
	_, isTrue := m.DB[tn]
	if isTrue {
		m.DB[tn].Data = d
		m.DB[tn].Time = t
		m.DB[tn].Line = l
		m.DB[tn].DevID = devId
	} else {
		m.DB[tn] = &MqttDBStr{
			Data:  d,
			Line:  l,
			Time:  t,
			DevID: devId,
		}
	}

}
func (m *MqttDBMap) SetLine(devId string, l bool) {
	for key, v := range m.DB {
		if v.DevID == devId {
			m.DB[key].Line = l
		}
	}
}
func (m *MqttDBMap) GetAll() map[string]*MqttDBStr {
	return m.DB
}
func (m *MqttDBMap) GetAllLine(b bool) *MqttDBMap {
	db := new(MqttDBMap)
	for k, v := range m.DB {
		if v.Line == b {
			db.Add(v.DevID, k, v.Data, v.Line, v.Time)
		}
	}
	return db
}

//==============================
// Mqtt客户端列表
type Mqttc struct {
	CID     string // 客户端ID
	CName   string //中文名称
	Line    bool   //当前状态
	UTime   int64  //上线时间
	Dtime   int64  //下线时间
	MesTime int64  //最后一次消息时间
	CIp     string //客户端IP
}
type MqttCs struct {
	DB map[string]*Mqttc
}

var MqttClient MqttCs

func (m *MqttCs) Add(ci, cn string, s bool, cip string) { //ci客户端ID，CN 中文名称，s 上下线状态，cip 客户端IP
	uTime := int64(0)
	dTime := int64(0)
	if s {
		uTime = time.Now().Unix()
	} else {
		dTime = time.Now().Unix()
	}

	m.DB[ci] = &Mqttc{
		CID:   ci,
		CName: cn,
		Line:  s,
		UTime: uTime,
		Dtime: dTime,
	}

}
func (m *MqttCs) FindCid(c string) bool {
	_, isTrue := m.DB[c]
	if isTrue {
		return true
	}
	return false
}
func (m *MqttCs) EditLine(c string, s bool) {
	m.DB[c].Line = s
	if s {
		m.DB[c].UTime = time.Now().Unix()
	} else {
		m.DB[c].Dtime = time.Now().Unix()
	}
}
func (m *MqttCs) GetCid(sl []string) []Mqttc {
	cl := []Mqttc{}
	for _, v := range sl {
		_, isTrue := m.DB[v]
		if isTrue {
			cl = append(cl, *m.DB[v])
		}
	}
	return cl
}
func (m *MqttCs) GetAll() map[string]*Mqttc {
	return m.DB
}

func (m *MqttCs) SetMesTime(c string, t int64) {
	_, isTrue := m.DB[c]
	if isTrue {
		if !m.DB[c].Line {
			m.DB[c].Line = true
		}
		m.DB[c].MesTime = t
	} else {
		m.Add(c, "", true, "")
		m.DB[c].MesTime = t
	}
}
func init() {
	MqttDBList.DB = map[string]*MqttDBStr{}
	MqttClient.DB = map[string]*Mqttc{}
}
